<template>
  <div class="roulette">
    <!-- 欢迎信息区域 -->
    <div class="welcome-section">
      <div class="welcome-card">
        <div class="welcome-avatar">
          <img v-if="userInfo.avatar" :src="userInfo.avatar" class="welcome-user-avatar" alt="用户头像" />
          <div v-else class="welcome-icon">
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M12 12C14.7614 12 17 9.76142 17 7C17 4.23858 14.7614 2 12 2C9.23858 2 7 4.23858 7 7C7 9.76142 9.23858 12 12 12Z" fill="currentColor"/>
              <path d="M12 14C7.58172 14 4 17.5817 4 22H20C20 17.5817 16.4183 14 12 14Z" fill="currentColor"/>
            </svg>
          </div>
        </div>
        <div class="welcome-content">
          <h2 class="welcome-title">欢迎参与抽奖</h2>
          <p class="welcome-username">{{ displayUsername || '用户' }}</p>
          <div class="welcome-subtitle">祝您好运连连！</div>
        </div>
      </div>
    </div>
    
    <!-- 左侧功能区域 -->
    <div class="left-sidebar">
      <div class="sidebar-card">
        <h3 class="sidebar-title">功能菜单</h3>
        <div class="sidebar-buttons">
          <button class="sidebar-btn profile-btn" @click="showProfile = true">
            <div class="btn-icon">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 12C14.7614 12 17 9.76142 17 7C17 4.23858 14.7614 2 12 2C9.23858 2 7 4.23858 7 7C7 9.76142 9.23858 12 12 12Z" fill="currentColor"/>
                <path d="M12 14C7.58172 14 4 17.5817 4 22H20C20 17.5817 16.4183 14 12 14Z" fill="currentColor"/>
              </svg>
            </div>
            <span>个人资料</span>
          </button>
          <button v-if="isTeacher" class="sidebar-btn admin-btn" @click="openUserManagement">
            <div class="btn-icon">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M16 4C16 6.20914 14.2091 8 12 8C9.79086 8 8 6.20914 8 4C8 1.79086 9.79086 0 12 0C14.2091 0 16 1.79086 16 4Z" fill="currentColor"/>
                <path d="M12 10C7.58172 10 4 13.5817 4 18V20C4 21.1046 4.89543 22 6 22H18C19.1046 22 20 21.1046 20 20V18C20 13.5817 16.4183 10 12 10Z" fill="currentColor"/>
                <path d="M20 2H22C23.1046 2 24 2.89543 24 4C24 5.10457 23.1046 6 22 6H20V8C20 9.10457 19.1046 10 18 10C16.8954 10 16 9.10457 16 8V6H14C12.8954 6 12 5.10457 12 4C12 2.89543 12.8954 2 14 2H16V0C16 -1.10457 16.8954 -2 18 -2C19.1046 -2 20 -1.10457 20 0V2Z" fill="currentColor"/>
              </svg>
            </div>
            <span>用户管理</span>
          </button>
        </div>
      </div>
    </div>
    
    <!-- 退出按钮区域 -->
    <div class="logout-section">
      <button class="logout-btn" @click="logout">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M9 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V5C3 4.46957 3.21071 3.96086 3.58579 3.58579C3.96086 3.21071 4.46957 3 5 3H9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          <path d="M16 17L21 12L16 7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          <path d="M21 12H9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
        <span>退出</span>
      </button>
    </div>
    
    <!-- 班主任设置奖品弹窗 -->
    <div v-if="isTeacher && showPrizeSettings" class="prize-settings-modal" @click="showPrizeSettings = false">
      <div class="prize-settings-content" @click.stop>
        <div class="modal-header">
          <h3>奖品设置</h3>
          <span class="close-modal" @click="showPrizeSettings = false">&times;</span>
        </div>
        <div class="modal-body">
          <div class="prize-form" v-for="(prize, index) in prizes" :key="index">
            <div class="prize-item">
              <span>奖品{{index+1}}</span>
              <button class="close-btn" @click="removePrize(index)">×</button>
            </div>
            <div class="form-group">
              <label>奖品名称：</label>
              <input type="text" v-model="prize.name" placeholder="奖品名称" />
            </div>
            <div class="form-group">
              <label>选择奖品图片：</label>
              <input type="file" :id="`file-input-${index}`" @change="handleImageUpload($event, index)" accept="image/*" style="display: none" />
              <button class="upload-btn" @click="triggerFileInput(index)">选择奖品图片</button>
              <img v-if="prize.image" :src="prize.image" class="prize-image" />
            </div>
            <div class="form-group">
              <label>中奖概率：</label>
              <select v-model="prize.probability">
                <option value="10">10</option>
                <option value="20">20</option>
                <option value="30">30</option>
                <option value="40">40</option>
                <option value="50">50</option>
              </select>
            </div>
            <div class="form-group">
              <label>总数量：</label>
              <input type="number" v-model.number="prize.total" placeholder="总数量" min="0" />
            </div>
            <div class="form-group">
              <label>剩余数量：</label>
              <input type="number" v-model.number="prize.remaining" placeholder="剩余数量" min="0" :max="prize.total || 0" />
              <span v-if="prize.total && prize.remaining > prize.total" class="error-text">剩余数量不能超过总数量</span>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="add-prize-btn" @click="addPrize">添加奖品</button>
          <button class="save-btn" @click="savePrizes" :disabled="isSaving">{{ isSaving ? '保存中...' : '确定' }}</button>
          <button class="cancel-btn" @click="showPrizeSettings = false">取消</button>
        </div>
      </div>
    </div>
    

    
    <!-- 转盘区域 -->
    <div class="wheel-container">
      <svg class="wheel" :style="{ transform: `rotate(${wheelRotation}deg)` }" width="400" height="400">
        <defs>
          <clipPath v-for="(prize, index) in prizes" :key="`clip-${index}`" :id="`sector-clip-${index}`">
            <path :d="getSectorPath(index)" />
          </clipPath>
        </defs>
        <g v-for="(prize, index) in prizes" :key="index">
          <path 
            :d="getSectorPath(index)" 
            :fill="getSectorColor(index)" 
            stroke="#fff" 
            stroke-width="2"
          />
          <!-- 奖品图片 -->
          <image 
            v-if="prize.image" 
            :x="getSectorImageX(index)" 
            :y="getSectorImageY(index)" 
            :width="getSectorImageSize()" 
            :height="getSectorImageSize()" 
            :href="prize.image" 
            :clip-path="`url(#sector-clip-${index})`"
            class="prize-image-svg"
            preserveAspectRatio="xMidYMid meet"
          />
          <!-- 奖品名称 -->
          <text 
            :x="getSectorTextX(index)" 
            :y="getSectorTextY(index)" 
            text-anchor="middle" 
            class="prize-name-svg"
          >
            {{ prize.name }}
          </text>
        </g>
      </svg>
      
      <div class="wheel-center" @click="spinWheel">
        <div class="go-button">GO</div>
      </div>
      
      <div class="control-buttons">
        <button v-if="isTeacher" class="settings-btn" @click="showPrizeSettings = true">
          设置奖品
        </button>
        <button v-if="isTeacher" class="records-btn" @click="showAllRecords = true">
          全部用户中奖记录
        </button>
        <button v-if="isTeacher" class="stock-btn" @click="showStockWindow = true">
          库存查看
        </button>
      </div>
    </div>
    
    <!-- 实时库存显示窗口 -->
    <div v-if="isTeacher && showStockWindow" class="stock-window" :class="{ 'minimized': stockWindowMinimized }">
      <div class="stock-header">
        <span>奖品库存</span>
        <div class="header-actions">
          <span class="minimize-btn" @click="stockWindowMinimized = !stockWindowMinimized">{{ stockWindowMinimized ? '▲' : '▼' }}</span>
          <span class="close-modal" @click="showStockWindow = false">&times;</span>
        </div>
      </div>
      <div v-if="!stockWindowMinimized" class="stock-content">
        <div class="stock-item" v-for="prize in prizes" :key="prize.id">
          <div class="stock-prize-info">
            <img v-if="prize.image" :src="prize.image" class="stock-prize-image" />
            <div class="stock-prize-details">
              <div class="stock-prize-name">{{ prize.name }}</div>
              <div class="stock-numbers">
                <span class="stock-remaining" :class="{ 'low-stock': (prize.remaining || 0) <= 5, 'out-of-stock': (prize.remaining || 0) === 0 }">
                  剩余: {{ prize.remaining || 0 }}
                </span>
                <span class="stock-total">总计: {{ prize.total || 0 }}</span>
              </div>
              <div class="stock-progress">
                <div class="stock-progress-bar" :style="{ width: getStockPercentage(prize) + '%', backgroundColor: getStockColor(prize) }"></div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="prizes.length === 0" class="no-stock-data">
          暂无奖品数据
        </div>
      </div>
    </div>
    
    <!-- 抽奖信息区域 -->
    <div class="info-section">
      <div class="attempts">剩余抽奖次数: {{ attemptsLeft }}</div>
    </div>
    
    <!-- 个人中奖记录 -->
    <div class="user-records">
      <h3>我的中奖记录</h3>
      <table class="records-table">
        <thead>
          <tr>
            <th>奖品名称</th>
            <th>奖品图片</th>
            <th>中奖时间</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(record, index) in userWinningRecords" :key="record.id || index + '_' + Date.now()">
            <td>{{ record.prizeName }}</td>
            <td class="prize-image-cell">
              <img v-if="record.prizeImage || getPrizeImage(record.prizeName)" 
                   :src="record.prizeImage || getPrizeImage(record.prizeName)" 
                   :alt="record.prizeName" 
                   class="prize-image-small" 
                   @error="handleImageError" />
              <span v-else class="no-image">暂无图片</span>
            </td>
            <td>{{ record.createTime ? new Date(record.createTime).toLocaleString() : record.date }}</td>
          </tr>
        </tbody>
      </table>
      <div v-if="userWinningRecords.length === 0" class="no-records">
        暂无中奖记录
      </div>
    </div>
    
    <!-- 全部用户中奖记录弹窗 -->
    <div v-if="isTeacher && showAllRecords" class="all-records-modal" @click="showAllRecords = false">
      <div class="all-records-content" @click.stop>
        <div class="modal-header">
          <h3>全部用户中奖记录</h3>
          <span class="close-modal" @click="showAllRecords = false">&times;</span>
        </div>
        <div class="modal-body">
          <table class="records-table">
            <thead>
              <tr>
                <th>中奖者</th>
                <th>奖品名称</th>
                <th>奖品图片</th>
                <th>联系方式</th>
                <th>中奖时间</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(record, index) in allWinningRecords" :key="record.id || index + '_' + Date.now()">
                <td>{{ record.username }}</td>
                <td>{{ record.prizeName }}</td>
                <td class="prize-image-cell">
                  <img v-if="record.prizeImage || getPrizeImage(record.prizeName)" 
                       :src="record.prizeImage || getPrizeImage(record.prizeName)" 
                       :alt="record.prizeName" 
                       class="prize-image-small" 
                       @error="handleImageError" />
                  <span v-else class="no-image">暂无图片</span>
                </td>
                <td>{{ record.phone || '暂无' }}</td>
                <td>{{ record.createTime ? new Date(record.createTime).toLocaleString() : record.date }}</td>
              </tr>
            </tbody>
          </table>
          <div v-if="allWinningRecords.length === 0" class="no-records">
            暂无中奖记录
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="showAllRecords = false">关闭</button>
        </div>
      </div>
    </div>

    <!-- 个人资料弹窗 -->
    <div v-if="showProfile" class="profile-modal" @click="showProfile = false">
      <div class="profile-content" @click.stop>
        <div class="modal-header">
          <h3>个人资料</h3>
          <div class="header-actions">
            <button v-if="!isEditingProfile" class="edit-btn" @click="startEditProfile">编辑</button>
            <button v-if="isEditingProfile" class="save-btn" @click="saveProfile">保存</button>
            <button v-if="isEditingProfile" class="cancel-edit-btn" @click="cancelEditProfile">取消</button>
            <span class="close-modal" @click="showProfile = false">&times;</span>
          </div>
        </div>
        <div class="modal-body">
          <div class="profile-info">
            <div class="profile-item">
              <label>登录用户名：</label>
              <span class="profile-value">{{ userInfo.username || displayUsername }}</span>
            </div>
            <div class="profile-item">
              <label>姓名：</label>
              <span v-if="!isEditingProfile" class="profile-value">{{ userInfo.name || '暂无数据' }}</span>
              <input v-else v-model="editUserInfo.name" type="text" class="edit-input" placeholder="请输入姓名" />
            </div>
            <div class="profile-item">
              <label>性别：</label>
              <span v-if="!isEditingProfile" class="profile-value">{{ getGenderText(userInfo.gender) }}</span>
              <select v-else v-model="editUserInfo.gender" class="edit-select">
                <option value="1">男</option>
                <option value="2">女</option>
              </select>
            </div>
            <div class="profile-item">
              <label>手机号码：</label>
              <span v-if="!isEditingProfile" class="profile-value">{{ userInfo.phone || '暂无数据' }}</span>
              <input v-else v-model="editUserInfo.phone" type="text" class="edit-input" placeholder="请输入手机号码" />
            </div>
            <div class="profile-item">
              <label>QQ号码：</label>
              <span v-if="!isEditingProfile" class="profile-value">{{ userInfo.qq || '暂无数据' }}</span>
              <input v-else v-model="editUserInfo.qq" type="text" class="edit-input" placeholder="请输入QQ号码" />
            </div>
            <div class="profile-item">
              <label>头像：</label>
              <div v-if="!isEditingProfile" class="profile-value">
                <img v-if="userInfo.avatar" :src="userInfo.avatar" class="user-avatar" alt="用户头像" />
                <span v-else>暂无头像</span>
              </div>
              <div v-else class="avatar-upload">
                <input type="file" ref="avatarInput" @change="handleAvatarUpload" accept="image/*" style="display: none" />
                <button class="upload-avatar-btn" @click="$refs.avatarInput.click()">选择头像</button>
                <img v-if="editUserInfo.avatar" :src="editUserInfo.avatar" class="preview-avatar" alt="预览头像" />
              </div>
            </div>
            <div class="profile-item">
              <label>我的地址：</label>
              <span v-if="!isEditingProfile" class="profile-value address-text">{{ userInfo.address || '暂无数据' }}</span>
              <textarea v-else v-model="editUserInfo.address" class="edit-textarea" placeholder="请输入地址" rows="2"></textarea>
            </div>
            <div class="profile-item">
              <label>创建时间：</label>
              <span class="profile-value">{{ userInfo.createTime ? formatDate(userInfo.createTime) : '暂无数据' }}</span>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button v-if="!isEditingProfile" class="edit-btn" @click="startEditProfile">编辑资料</button>
          <button v-if="isEditingProfile" class="save-btn" @click="saveProfile">保存</button>
          <button v-if="isEditingProfile" class="cancel-btn" @click="cancelEditProfile">取消</button>
          <button v-if="!isEditingProfile" class="cancel-btn" @click="showProfile = false">关闭</button>
        </div>
      </div>
    </div>

    <!-- 用户管理弹窗 -->
    <div v-if="isTeacher && showUserManagement" class="user-management-modal" @click="showUserManagement = false">
      <div class="user-management-content" @click.stop>
        <div class="modal-header">
          <h3>用户管理</h3>
          <span class="close-modal" @click="showUserManagement = false">&times;</span>
        </div>
        <div class="modal-body">
          <div class="user-management-tools">
            <button class="refresh-btn" @click="fetchAllUsers">刷新用户列表</button>
            <div class="search-box">
              <input type="text" v-model="userSearchQuery" placeholder="搜索用户名..." @input="filterUsers" />
            </div>
          </div>
          <table class="users-table">
            <thead>
              <tr>
                <th>头像</th>
                <th>用户ID</th>
                <th>用户名</th>
                <th>姓名</th>
                <th>性别</th>
                <th>职位</th>
                <th>手机号</th>
                <th>QQ号</th>
                <th>地址</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in filteredUsers" :key="user.id">
                <td>
                  <div class="user-avatar-cell">
                    <img v-if="user.avatar" :src="user.avatar" class="table-user-avatar" alt="头像" />
                    <div v-else class="default-avatar">无</div>
                  </div>
                </td>
                <td>{{ user.id }}</td>
                <td>{{ user.username }}</td>
                <td>{{ user.name || '暂无' }}</td>
                <td>{{ getGenderText(user.gender) }}</td>
                <td>{{ getJobText(user.job) }}</td>
                <td>{{ user.phone || '暂无' }}</td>
                <td>{{ user.qq || '暂无' }}</td>
                <td>{{ user.address || '暂无' }}</td>
                <td>
                  <button class="action-btn edit-btn" @click="editUser(user)">编辑</button>
                  <button class="action-btn delete-btn" @click="deleteUser(user)">删除</button>
                </td>
              </tr>
            </tbody>
          </table>
          <div v-if="filteredUsers.length === 0" class="no-users">
            暂无用户数据
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="showUserManagement = false">关闭</button>
        </div>
      </div>
    </div>

    <!-- 用户编辑弹窗 -->
    <div v-if="showEditUser" class="edit-user-modal" @click="showEditUser = false">
      <div class="edit-user-content" @click.stop>
        <div class="modal-header">
          <h3>编辑用户信息</h3>
          <span class="close-modal" @click="showEditUser = false">&times;</span>
        </div>
        <div class="modal-body">
          <div class="edit-user-info">
            <div class="edit-profile-item">
              <label>登录用户名：</label>
              <input type="text" v-model="editingUser.username" class="edit-input" readonly />
            </div>
            <div class="edit-profile-item">
              <label>姓名：</label>
              <input type="text" v-model="editingUser.name" class="edit-input" placeholder="请输入姓名" />
            </div>
            <div class="edit-profile-item">
              <label>性别：</label>
              <select v-model="editingUser.gender" class="edit-select">
                <option :value="1">男</option>
                <option :value="2">女</option>
              </select>
            </div>
            <div class="edit-profile-item">
              <label>职位：</label>
              <select v-model="editingUser.job" class="edit-select">
                <option :value="1">班主任</option>
                <option :value="2">讲师</option>
                <option :value="3">学工主管</option>
                <option :value="4">学生</option>
              </select>
            </div>
            <div class="edit-profile-item">
              <label>手机号码：</label>
              <input type="text" v-model="editingUser.phone" class="edit-input" placeholder="请输入手机号码" />
            </div>
            <div class="edit-profile-item">
              <label>QQ号码：</label>
              <input type="text" v-model="editingUser.qq" class="edit-input" placeholder="请输入QQ号码" />
            </div>
            <div class="edit-profile-item">
              <label>头像：</label>
              <div class="avatar-upload">
                <input type="file" ref="editAvatarInput" @change="handleEditAvatarUpload" accept="image/*" style="display: none" />
                <button class="upload-avatar-btn" @click="$refs.editAvatarInput.click()">选择头像</button>
                <img v-if="editingUser.avatar" :src="editingUser.avatar" class="preview-avatar" alt="预览头像" />
              </div>
            </div>
            <div class="edit-profile-item">
              <label>地址：</label>
              <textarea v-model="editingUser.address" class="edit-textarea" placeholder="请输入地址" rows="2"></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="save-btn" @click="saveUserEdit">保存</button>
          <button class="cancel-btn" @click="showEditUser = false">取消</button>
        </div>
      </div>
    </div>

    <!-- 中奖弹窗 -->
    <div v-if="showWinModal" class="win-modal" @click="closeWinModal">
      <div class="modal-content" @click.stop>
        <span class="close" @click="closeWinModal">&times;</span>
        <h2>恭喜中奖！</h2>
        <img v-if="currentPrize && currentPrize.image" :src="currentPrize.image" class="prize-image-large" />
        <h3>{{ currentPrize ? currentPrize.name : '' }}</h3>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'HomePage',
  setup() {
    const store = useStore()
    const router = useRouter()
    
    // 响应式数据
    const prizes = ref([])
    const wheelRotation = ref(0)
    const isSpinning = ref(false)
    const showWinModal = ref(false)
    const currentPrize = ref(null)
    const userWinningRecords = ref([])
    const allWinningRecords = ref([])
    const attemptsLeft = ref(3)
    const showPrizeSettings = ref(false)
    const showAllRecords = ref(false)
    const isTeacher = ref(false)
    const currentUserId = ref(null)
    const username = ref('')
    const isSaving = ref(false)
    const showStockWindow = ref(false)
    const stockWindowMinimized = ref(false)
    
    // 新增的响应式数据
    const showProfile = ref(false)
    const showUserManagement = ref(false)
    const userInfo = ref({})
    const userStats = ref({})
    const allUsers = ref([])
    const filteredUsers = ref([])
    const userSearchQuery = ref('')
    
    // 编辑个人资料相关
    const isEditingProfile = ref(false)
    const editUserInfo = ref({})
    const originalUserInfo = ref({})
    
    // 用户编辑相关
    const showEditUser = ref(false)
    const editingUser = ref({})
    
    // 定时刷新库存数据
    let stockRefreshInterval = null
    
    // 计算属性
    const isAuthenticated = computed(() => store.getters.isAuthenticated)
    const displayUsername = computed(() => {
      return store.state.username || username.value || '用户'
    })
    
    // 计算中奖率
    const winRate = computed(() => {
      const totalDraws = userStats.value.totalDraws || 0
      const totalWins = userStats.value.totalWins || 0
      if (totalDraws === 0) return 0
      return Math.round((totalWins / totalDraws) * 100)
    })
    
    // 页面可见性变化处理函数
    let handleVisibilityChange = null
    
    // 添加页面可见性变化监听器
    const addVisibilityChangeListener = () => {
      handleVisibilityChange = () => {
        if (!document.hidden && currentUserId.value) {
          console.log('页面变为可见，刷新数据...')
          // 页面变为可见时，强制刷新数据
          setTimeout(async () => {
            try {
              // 如果用户正在编辑奖品设置，则跳过自动刷新
              if (showPrizeSettings.value) {
                console.log('用户正在编辑奖品设置，跳过页面可见性刷新')
                return
              }
              await loadPrizes(true)
              await fetchUserWinningRecords(true)
              if (isTeacher.value) {
                await fetchAllWinningRecords(true)
              }
              console.log('页面可见性变化后数据刷新完成')
            } catch (error) {
              console.error('页面可见性变化后数据刷新失败:', error)
            }
          }, 500) // 延迟500ms确保页面完全可见
        }
      }
      
      document.addEventListener('visibilitychange', handleVisibilityChange)
    }
    
    // 移除页面可见性变化监听器
    const removeVisibilityChangeListener = () => {
      if (handleVisibilityChange) {
        document.removeEventListener('visibilitychange', handleVisibilityChange)
      }
    }
    
    // 获取当前用户ID
    const getCurrentUserId = async () => {
      if (!isAuthenticated.value) {
        console.log('用户未登录，重定向到登录页面')
        router.push('/UserLogin')
        return false
      }
      
      try {
        const response = await fetch('/users/current', {
          headers: {
            'Authorization': `Bearer ${store.state.token}`
          }
        })
        const result = await response.json()
        
        if (result.code === 1 && result.data && result.data.id) {
          currentUserId.value = result.data.id
          console.log('获取到用户ID:', currentUserId.value)
          return true
        } else {
          const username = store.state.username
          if (username) {
            const userResponse = await fetch(`/users/by-username?username=${encodeURIComponent(username)}`)
            const userData = await userResponse.json()
            
            if (userData.code === 1 && userData.data && userData.data.id) {
              currentUserId.value = userData.data.id
              console.log('通过用户名获取到用户ID:', currentUserId.value)
              return true
            }
          }
          
          console.warn('无法获取用户ID，使用默认ID: 1')
          currentUserId.value = 1
          return true
        }
      } catch (error) {
        console.error('获取用户ID失败:', error)
        console.warn('使用默认ID: 1')
        currentUserId.value = 1
        return true
      }
    }
    
    // 检查用户角色
    const checkUserRole = async () => {
      if (!store.state.token) {
        console.log('没有token，无法检查权限')
        return
      }
      
      try {
        console.log('开始检查用户权限，token:', store.state.token.substring(0, 20) + '...')
        const response = await fetch('/prizes/permission', {
          headers: {
            'Authorization': `Bearer ${store.state.token}`
          }
        })
        const result = await response.json()
        console.log('权限检查响应:', result)
        isTeacher.value = result.data
        console.log('设置isTeacher为:', isTeacher.value)
      } catch (error) {
        console.error('检查用户权限失败:', error)
        isTeacher.value = false
      }
    }
    
    // 获取用户中奖记录
    const fetchUserWinningRecords = async (forceRefresh = false) => {
      console.log('开始获取用户中奖记录，当前用户ID:', currentUserId.value, '强制刷新:', forceRefresh)
      
      if (!currentUserId.value) {
        const userIdObtained = await getCurrentUserId()
        if (!userIdObtained) {
          console.error('无法获取用户ID，无法加载中奖记录')
          return
        }
      }
      
      try {
        const timestamp = new Date().getTime()
        const url = forceRefresh 
          ? `/prizes/records/user?t=${timestamp}&limit=1000` 
          : '/prizes/records/user?limit=1000'
        
        console.log('请求中奖记录URL:', url)
        
        const response = await fetch(url, {
          headers: {
            'Authorization': `Bearer ${store.state.token}`,
            'Cache-Control': 'no-cache, no-store, must-revalidate',
            'Pragma': 'no-cache',
            'Expires': '0'
          }
        })
        
        const result = await response.json()
        console.log('中奖记录请求响应数据:', result)
        
        if (result.code === 1) {
          userWinningRecords.value = Array.isArray(result.data) 
            ? result.data.sort((a, b) => {
                const timeA = a.createTime ? new Date(a.createTime).getTime() : 0
                const timeB = b.createTime ? new Date(b.createTime).getTime() : 0
                return timeB - timeA
              })
            : []
          console.log('用户中奖记录设置成功，共', userWinningRecords.value.length, '条记录')
          
          localStorage.setItem('userWinningRecords', JSON.stringify(userWinningRecords.value))
        } else {
          console.error('获取中奖记录失败，响应码:', result.code, '消息:', result.msg)
          loadWinningRecordsFromLocalStorage()
        }
      } catch (error) {
        console.error('获取用户中奖记录失败:', error)
        loadWinningRecordsFromLocalStorage()
      }
    }
    
    // 获取所有中奖记录
    const fetchAllWinningRecords = async (forceRefresh = false) => {
      if (!isTeacher.value) return
      
      try {
        const timestamp = new Date().getTime()
        const url = forceRefresh 
          ? `/prizes/records/all?t=${timestamp}&limit=1000` 
          : '/prizes/records/all?limit=1000'
        
        console.log('请求所有中奖记录URL:', url)
        
        const response = await fetch(url, {
          headers: {
            'Authorization': `Bearer ${store.state.token}`,
            'Cache-Control': 'no-cache, no-store, must-revalidate',
            'Pragma': 'no-cache',
            'Expires': '0'
          }
        })
        
        const result = await response.json()
        
        if (result.code === 1) {
          allWinningRecords.value = Array.isArray(result.data) 
            ? result.data.sort((a, b) => {
                const timeA = a.createTime ? new Date(a.createTime).getTime() : 0
                const timeB = b.createTime ? new Date(b.createTime).getTime() : 0
                return timeB - timeA
              })
            : []
          console.log('所有中奖记录设置成功，共', allWinningRecords.value.length, '条记录')
          
          localStorage.setItem('allWinningRecords', JSON.stringify(allWinningRecords.value))
        } else {
          console.error('获取所有中奖记录失败，响应码:', result.code, '消息:', result.msg)
          loadAllWinningRecordsFromLocalStorage()
        }
      } catch (error) {
        console.error('获取所有中奖记录失败:', error)
        loadAllWinningRecordsFromLocalStorage()
      }
    }
    
    // 从本地存储加载中奖记录
    const loadWinningRecordsFromLocalStorage = () => {
      try {
        const savedRecords = localStorage.getItem('userWinningRecords')
        if (savedRecords) {
          userWinningRecords.value = JSON.parse(savedRecords)
          console.log('从本地存储加载了', userWinningRecords.value.length, '条中奖记录')
        } else {
          console.log('本地存储中没有中奖记录')
        }
      } catch (error) {
        console.error('从本地存储加载中奖记录失败:', error)
        userWinningRecords.value = []
      }
    }
    
    // 从本地存储加载所有中奖记录
    const loadAllWinningRecordsFromLocalStorage = () => {
      try {
        const savedRecords = localStorage.getItem('allWinningRecords')
        if (savedRecords) {
          allWinningRecords.value = JSON.parse(savedRecords)
          console.log('从本地存储加载了', allWinningRecords.value.length, '条所有中奖记录')
        } else {
          console.log('本地存储中没有所有中奖记录')
        }
      } catch (error) {
        console.error('从本地存储加载所有中奖记录失败:', error)
        allWinningRecords.value = []
      }
    }
    
    // 初始化
    onMounted(async () => {
      console.log('组件挂载，开始初始化...')
      
      // 先尝试从本地存储加载中奖记录
      loadWinningRecordsFromLocalStorage()
      loadAllWinningRecordsFromLocalStorage()
      
      // 检查用户是否已登录并获取用户ID
      const userIdObtained = await getCurrentUserId()
      
      if (userIdObtained) {
        console.log('成功获取用户ID:', currentUserId.value, '开始加载数据...')
        await checkUserRole()
        
        // 加载奖品数据
        await loadPrizes(true)
        
        // 初始加载时使用强制刷新，获取最新数据
        try {
          await fetchUserWinningRecords(true)
          if (isTeacher.value) {
            await fetchAllWinningRecords(true)
            await fetchAllUsers() // 获取所有用户列表
          }
          // 获取用户信息和统计
          await fetchUserInfo()
          await fetchUserStats()
          console.log('初始化数据加载完成')
        } catch (error) {
          console.error('初始化加载数据失败:', error)
        }
      } else {
        console.warn('未能获取用户ID，将使用本地存储的数据')
        // 即使没有用户ID，也要加载奖品数据
        await loadPrizes(true)
      }
      
      // 添加页面可见性变化监听器
      addVisibilityChangeListener()
      
      // 开始库存定时刷新
      startStockRefresh()
    })
    
    // 清理
    onUnmounted(() => {
      removeVisibilityChangeListener()
      stopStockRefresh()
    })
    
    // 加载奖品数据
    const loadPrizes = async (forceRefresh = false) => {
      try {
        const timestamp = forceRefresh ? `?t=${new Date().getTime()}` : ''
        const response = await fetch(`/prizes/list${timestamp}`, {
          headers: forceRefresh ? {
            'Cache-Control': 'no-cache, no-store, must-revalidate',
            'Pragma': 'no-cache',
            'Expires': '0'
          } : {}
        })
        const result = await response.json()
        
        if (result.code === 1 && Array.isArray(result.data)) {
          prizes.value = result.data.map(prize => {
            // 过滤掉无效的图片路径，避免404错误
            let imageUrl = prize.image || prize.imageUrl || ''
            if (imageUrl && imageUrl.includes('/api/uploads/images/')) {
              // 如果是无效的上传路径，设置为空
              imageUrl = ''
            }
            return {
              id: prize.id,
              name: prize.name,
              image: imageUrl,
              probability: prize.probability || 10,
              points: prize.points || 0,
              total: prize.total || 0,
              remaining: prize.remaining || 0
            }
          })
        } else {
          // 如果没有奖品数据，使用默认奖品
          prizes.value = [
            { id: 1, name: '奖品1', image: '', probability: 20, points: 10, total: 100, remaining: 100 },
            { id: 2, name: '奖品2', image: '', probability: 20, points: 20, total: 100, remaining: 100 },
            { id: 3, name: '奖品3', image: '', probability: 20, points: 30, total: 100, remaining: 100 },
            { id: 4, name: '奖品4', image: '', probability: 20, points: 40, total: 100, remaining: 100 },
            { id: 5, name: '奖品5', image: '', probability: 20, points: 50, total: 100, remaining: 100 }
          ]
        }
        console.log('加载奖品数据:', prizes.value)
      } catch (error) {
        console.error('加载奖品失败:', error)
        // 使用默认奖品
        prizes.value = [
          { id: 1, name: '奖品1', image: '', probability: 20, points: 10, total: 100, remaining: 100 },
          { id: 2, name: '奖品2', image: '', probability: 20, points: 20, total: 100, remaining: 100 },
          { id: 3, name: '奖品3', image: '', probability: 20, points: 30, total: 100, remaining: 100 },
          { id: 4, name: '奖品4', image: '', probability: 20, points: 40, total: 100, remaining: 100 },
          { id: 5, name: '奖品5', image: '', probability: 20, points: 50, total: 100, remaining: 100 }
        ]
      }
    }
    
    // 添加奖品
    const addPrize = () => {
      prizes.value.push({
        id: Date.now(),
        name: '',
        image: '',
        probability: 10,
        points: 0,
        total: 100,
        remaining: 100
      })
    }
    
    // 移除奖品
    const removePrize = async (index) => {
      if (prizes.value.length > 1) {
        const prize = prizes.value[index]
        
        // 如果是已存在的奖品（ID小于1000），需要调用删除接口
        if (prize.id && prize.id < 1000) {
          try {
            const response = await fetch(`/prizes/${prize.id}`, {
              method: 'DELETE',
              headers: {
                'Authorization': `Bearer ${store.state.token}`
              }
            })
            
            const result = await response.json()
            console.log('删除奖品响应:', result)
            if (result.code !== 1) {
              ElMessage.error('删除失败: ' + (result.msg || result.message || '未知错误'))
              return
            }
          } catch (error) {
            console.error('删除奖品失败:', error)
            ElMessage.error('删除失败')
            return
          }
        }
        
        // 从本地数组中移除
        prizes.value.splice(index, 1)
        ElMessage.success('奖品删除成功')
      }
    }
    
    // 验证奖品数据
    const validatePrizes = () => {
      for (let i = 0; i < prizes.value.length; i++) {
        const prize = prizes.value[i]
        if (!prize.name || prize.name.trim() === '') {
          ElMessage.error(`请填写第${i + 1}个奖品的名称`)
          return false
        }
        if (!prize.probability || prize.probability <= 0) {
          ElMessage.error(`请设置第${i + 1}个奖品的中奖概率`)
          return false
        }
        if (prize.total === undefined || prize.total === null || prize.total < 0) {
          ElMessage.error(`请设置第${i + 1}个奖品的总数量`)
          return false
        }
        if (prize.remaining === undefined || prize.remaining === null || prize.remaining < 0) {
          ElMessage.error(`请设置第${i + 1}个奖品的剩余数量`)
          return false
        }
        if (prize.remaining > prize.total) {
          ElMessage.error(`第${i + 1}个奖品的剩余数量不能超过总数量`)
          return false
        }
      }
      return true
    }
    
    // 保存奖品设置
    const savePrizes = async () => {
      // 验证数据
      if (!validatePrizes()) {
        return
      }
      
      if (isSaving.value) {
        return // 防止重复提交
      }
      
      isSaving.value = true
      
      try {
        let allSuccess = true
        let errorMessage = ''
        
        for (const prize of prizes.value) {
          try {
            let response
            if (prize.id && prize.id > 1000) {
              // 新添加的奖品（使用时间戳作为临时ID）
              // 注意：新增时不传递ID，让数据库自动生成
              response = await fetch('/prizes', {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                  'Authorization': `Bearer ${store.state.token}`
                },
                body: JSON.stringify({
                  name: prize.name,
                  imageUrl: prize.image && !prize.image.includes('/api/uploads/images/') ? prize.image : '',
                  probability: prize.probability,
                  points: prize.points || 0,
                  total: prize.total || 100,
                  remaining: prize.remaining || 100,
                  enabled: true
                  // 不传递id字段，让数据库自动生成
                })
              })
            } else if (prize.id && prize.id <= 1000) {
              // 更新现有奖品（ID小于等于1000的是数据库中的真实奖品）
              response = await fetch(`/prizes/${prize.id}`, {
                method: 'PUT',
                headers: {
                  'Content-Type': 'application/json',
                  'Authorization': `Bearer ${store.state.token}`
                },
                body: JSON.stringify({
                  name: prize.name,
                  imageUrl: prize.image && !prize.image.includes('/api/uploads/images/') ? prize.image : '',
                  probability: prize.probability,
                  points: prize.points || 0,
                  total: prize.total || 100,
                  remaining: prize.remaining || 100,
                  enabled: true
                })
              })
            } else {
              // 没有ID的新奖品，也进行新增操作
              response = await fetch('/prizes', {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                  'Authorization': `Bearer ${store.state.token}`
                },
                body: JSON.stringify({
                  name: prize.name,
                  imageUrl: prize.image && !prize.image.includes('/api/uploads/images/') ? prize.image : '',
                  probability: prize.probability,
                  points: prize.points || 0,
                  total: prize.total || 100,
                  remaining: prize.remaining || 100,
                  enabled: true
                  // 不传递id字段，让数据库自动生成
                })
              })
            }
            
            if (response) {
              const result = await response.json()
              console.log('保存奖品响应:', result)
              if (result.code !== 1) {
                allSuccess = false
                errorMessage = result.msg || result.message || '保存失败'
                break
              }
            }
          } catch (error) {
            console.error('保存奖品失败:', error)
            allSuccess = false
            errorMessage = `保存奖品"${prize.name}"时发生网络错误`
            break
          }
        }
        
        if (allSuccess) {
          ElMessage.success('奖品设置保存成功')
          showPrizeSettings.value = false
          // 保存成功后延迟刷新数据，避免覆盖用户修改
          setTimeout(async () => {
            await loadPrizes(true)
          }, 1000)
        } else {
          ElMessage.error('保存失败: ' + errorMessage)
        }
      } catch (error) {
        console.error('保存奖品设置失败:', error)
        ElMessage.error('保存失败')
      } finally {
        isSaving.value = false
      }
    }
    
    // 获取扇形路径
    const getSectorPath = (index) => {
      const centerX = 200
      const centerY = 200
      const radius = 180
      const anglePerSector = 360 / prizes.value.length
      const startAngle = index * anglePerSector
      const endAngle = (index + 1) * anglePerSector
      
      const startAngleRad = (startAngle * Math.PI) / 180
      const endAngleRad = (endAngle * Math.PI) / 180
      
      const x1 = centerX + radius * Math.cos(startAngleRad)
      const y1 = centerY + radius * Math.sin(startAngleRad)
      const x2 = centerX + radius * Math.cos(endAngleRad)
      const y2 = centerY + radius * Math.sin(endAngleRad)
      
      const largeArcFlag = anglePerSector > 180 ? 1 : 0
      
      return `M ${centerX} ${centerY} L ${x1} ${y1} A ${radius} ${radius} 0 ${largeArcFlag} 1 ${x2} ${y2} Z`
    }
    
    // 获取扇形颜色
    const getSectorColor = (index) => {
      const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8', '#F7DC6F']
      return colors[index % colors.length]
    }
    
    // 获取扇形图片X坐标
    const getSectorImageX = (index) => {
      const centerX = 200
      const radius = 80 // 图片距离中心的距离
      const anglePerSector = 360 / prizes.value.length
      const angle = index * anglePerSector + anglePerSector / 2
      const angleRad = (angle * Math.PI) / 180
      const imageSize = getSectorImageSize()
      return centerX + radius * Math.cos(angleRad) - imageSize / 2
    }
    
    // 获取扇形图片Y坐标
    const getSectorImageY = (index) => {
      const centerY = 200
      const radius = 80 // 图片距离中心的距离
      const anglePerSector = 360 / prizes.value.length
      const angle = index * anglePerSector + anglePerSector / 2
      const angleRad = (angle * Math.PI) / 180
      const imageSize = getSectorImageSize()
      return centerY + radius * Math.sin(angleRad) - imageSize / 2
    }
    
    // 获取扇形图片大小
    const getSectorImageSize = () => {
      const prizeCount = prizes.value.length
      // 根据奖品数量动态调整图片大小
      if (prizeCount <= 4) return 50
      if (prizeCount <= 6) return 40
      if (prizeCount <= 8) return 35
      return 30
    }
    
    // 获取扇形文字X坐标
    const getSectorTextX = (index) => {
      const centerX = 200
      const radius = 140 // 文字距离中心的距离，比图片更远
      const anglePerSector = 360 / prizes.value.length
      const angle = index * anglePerSector + anglePerSector / 2
      const angleRad = (angle * Math.PI) / 180
      return centerX + radius * Math.cos(angleRad)
    }
    
    // 获取扇形文字Y坐标
    const getSectorTextY = (index) => {
      const centerY = 200
      const radius = 140 // 文字距离中心的距离，比图片更远
      const anglePerSector = 360 / prizes.value.length
      const angle = index * anglePerSector + anglePerSector / 2
      const angleRad = (angle * Math.PI) / 180
      return centerY + radius * Math.sin(angleRad) + 5
    }
    
    // 转动轮盘
    const spinWheel = async () => {
      if (isSpinning.value || attemptsLeft.value <= 0) {
        if (attemptsLeft.value <= 0) {
          ElMessage.warning('抽奖次数已用完')
        }
        return
      }
      
      if (!currentUserId.value) {
        ElMessage.error('请先登录')
        return
      }
      
      isSpinning.value = true
      
      try {
        // 调用抽奖接口
        const response = await fetch('/prizes/draw', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${store.state.token}`
          }
        })
        
        const result = await response.json()
        console.log('抽奖结果:', result)
        
        if (result.code === 1) {
          // 减少抽奖次数
          attemptsLeft.value--
          
          // 找到中奖奖品的索引
          let winningIndex = 0
          if (result.data && result.data.name) {
            const foundIndex = prizes.value.findIndex(prize => prize.name === result.data.name)
            if (foundIndex !== -1) {
              winningIndex = foundIndex
            }
          }
          
          // 计算转动角度
          const anglePerSector = 360 / prizes.value.length
          const targetAngle = winningIndex * anglePerSector + anglePerSector / 2
          const spinAngle = 360 * 5 + (360 - targetAngle) // 转5圈后停在目标位置
          
          wheelRotation.value += spinAngle
          
          // 等待转动完成后显示结果
          setTimeout(() => {
            isSpinning.value = false
            
            if (result.data) {
              currentPrize.value = result.data
              showWinModal.value = true
              
              // 延迟刷新数据，等待后端消息队列处理完成
              setTimeout(async () => {
                await fetchUserWinningRecords(true)
                if (isTeacher.value) {
                  await fetchAllWinningRecords(true)
                }
                // 立即刷新库存数据
                await loadPrizes(true)
              }, 2000)
            }
          }, 4000)
        } else {
          isSpinning.value = false
          ElMessage.error(result.msg || '抽奖失败，请稍后再试')
        }
      } catch (error) {
        isSpinning.value = false
        console.error('抽奖失败:', error)
        ElMessage.error('抽奖失败，请检查您的网络连接或稍后再试')
      }
    }
    
    // 关闭中奖弹窗
    const closeWinModal = () => {
      showWinModal.value = false
      currentPrize.value = null
    }
    
    // 触发文件选择
    const triggerFileInput = (index) => {
      const fileInput = document.getElementById(`file-input-${index}`)
      if (fileInput) {
        fileInput.click()
      }
    }
    
    // 处理图片上传
    const handleImageUpload = (event, index) => {
      const file = event.target.files[0]
      if (!file) return
      
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        ElMessage.error('请选择图片文件')
        return
      }
      
      // 检查文件大小（限制为500KB，确保Base64后不超过数据库限制）
      if (file.size > 500 * 1024) {
        ElMessage.error('图片大小不能超过500KB，请选择更小的图片或进行压缩')
        return
      }
      
      // 创建canvas来压缩图片
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      const img = new Image()
      
      img.onload = () => {
        // 设置最大尺寸
        const maxWidth = 200
        const maxHeight = 200
        let { width, height } = img
        
        // 计算缩放比例
        if (width > height) {
          if (width > maxWidth) {
            height = (height * maxWidth) / width
            width = maxWidth
          }
        } else {
          if (height > maxHeight) {
            width = (width * maxHeight) / height
            height = maxHeight
          }
        }
        
        // 设置canvas尺寸
        canvas.width = width
        canvas.height = height
        
        // 绘制压缩后的图片
        ctx.drawImage(img, 0, 0, width, height)
        
        // 转换为Base64，使用较低的质量以减小文件大小
        const compressedDataUrl = canvas.toDataURL('image/jpeg', 0.7)
        
        // 检查压缩后的大小（Base64编码后大约是原始数据的4/3）
        if (compressedDataUrl.length > 400000) { // 约300KB的Base64数据
          ElMessage.error('图片压缩后仍然过大，请选择更小的图片')
          return
        }
        
        // 将压缩后的图片数据设置到奖品对象中
        prizes.value[index].image = compressedDataUrl
        ElMessage.success('图片上传并压缩成功')
      }
      
      img.onerror = () => {
        ElMessage.error('图片加载失败，请选择有效的图片文件')
      }
      
      // 创建FileReader来读取文件
      const reader = new FileReader()
      reader.onload = (e) => {
        img.src = e.target.result
      }
      reader.readAsDataURL(file)
    }
    
    // 根据奖品名称获取奖品图片
    const getPrizeImage = (prizeName) => {
      const prize = prizes.value.find(p => p.name === prizeName)
      return prize ? prize.image : ''
    }
    
    // 图片加载错误处理
    const handleImageError = (event) => {
      event.target.style.display = 'none'
      const noImageSpan = event.target.nextElementSibling
      if (noImageSpan && noImageSpan.classList.contains('no-image')) {
        noImageSpan.style.display = 'inline'
      }
    }
    
    // 获取库存百分比
    const getStockPercentage = (prize) => {
      if (!prize.total || prize.total === 0) return 0
      return Math.max(0, Math.min(100, (prize.remaining / prize.total) * 100))
    }
    
    // 获取库存颜色
    const getStockColor = (prize) => {
      const percentage = getStockPercentage(prize)
      if (percentage === 0) return '#ff4757' // 红色 - 无库存
      if (percentage <= 20) return '#ffa502' // 橙色 - 低库存
      if (percentage <= 50) return '#ffb142' // 黄色 - 中等库存
      return '#2ed573' // 绿色 - 充足库存
    }
    
    // 开始库存定时刷新
    const startStockRefresh = () => {
      if (stockRefreshInterval) {
        clearInterval(stockRefreshInterval)
      }
      stockRefreshInterval = setInterval(async () => {
        try {
          // 如果用户正在编辑奖品设置，则跳过自动刷新
          if (showPrizeSettings.value) {
            console.log('用户正在编辑奖品设置，跳过库存自动刷新')
            return
          }
          await loadPrizes(true)
          console.log('库存数据自动刷新完成')
        } catch (error) {
          console.error('库存数据自动刷新失败:', error)
        }
      }, 5000) // 每5秒刷新一次
    }
    
    // 停止库存定时刷新
    const stopStockRefresh = () => {
      if (stockRefreshInterval) {
        clearInterval(stockRefreshInterval)
        stockRefreshInterval = null
      }
    }
    
    // 退出登录
    const logout = () => {
      // 清除用户认证状态
      store.dispatch('logout')
      
      // 清除本地存储的中奖记录
      localStorage.removeItem('userWinningRecords')
      localStorage.removeItem('allWinningRecords')
      
      // 停止库存刷新
      stopStockRefresh()
      
      // 移除页面可见性监听器
      removeVisibilityChangeListener()
      
      // 跳转到登录页面
      router.push('/UserLogin')
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '暂无数据'
      try {
        return new Date(dateString).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        })
      } catch (error) {
        return '日期格式错误'
      }
    }
    
    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        const response = await fetch('/users/current', {
          headers: {
            'Authorization': `Bearer ${store.state.token}`
          }
        })
        const result = await response.json()
        if (result.code === 1 && result.data) {
          userInfo.value = result.data
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
    }
    
    // 获取用户统计信息
    const fetchUserStats = async () => {
      try {
        const response = await fetch('/prizes/user-stats', {
          headers: {
            'Authorization': `Bearer ${store.state.token}`
          }
        })
        const result = await response.json()
        if (result.code === 1 && result.data) {
          userStats.value = result.data
        } else {
          // 如果没有统计接口，从中奖记录计算
          userStats.value = {
            totalDraws: userWinningRecords.value.length + (3 - attemptsLeft.value),
            totalWins: userWinningRecords.value.length
          }
        }
      } catch (error) {
        console.error('获取用户统计失败:', error)
        // 从中奖记录计算统计信息
        userStats.value = {
          totalDraws: userWinningRecords.value.length + (3 - attemptsLeft.value),
          totalWins: userWinningRecords.value.length
        }
      }
    }
    
    // 打开用户管理弹窗
    const openUserManagement = async () => {
      showUserManagement.value = true
      console.log('打开用户管理弹窗，开始获取用户列表')
      await fetchAllUsers()
    }

    // 获取所有用户
    const fetchAllUsers = async () => {
      console.log('fetchAllUsers被调用，isTeacher:', isTeacher.value)
      if (!isTeacher.value) {
        console.log('用户不是老师，跳过获取用户列表')
        return
      }
      try {
        console.log('开始获取用户列表，token存在:', !!store.state.token)
        const response = await fetch('/users', {
          headers: {
            'Authorization': `Bearer ${store.state.token}`
          }
        })
        const result = await response.json()
        console.log('用户列表API响应:', result)
        
        if (result.code === 1 && result.data) {
          allUsers.value = result.data
          filteredUsers.value = result.data
          console.log('成功获取用户列表，共', result.data.length, '个用户')
          ElMessage.success(`成功加载${result.data.length}个用户`)
        } else {
          console.error('获取用户列表失败，响应码:', result.code, '消息:', result.msg)
          ElMessage.error(result.msg || '获取用户列表失败')
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败：' + error.message)
      }
    }
    
    // 过滤用户
    const filterUsers = () => {
      if (!userSearchQuery.value.trim()) {
        filteredUsers.value = allUsers.value
      } else {
        filteredUsers.value = allUsers.value.filter(user => 
          user.username.toLowerCase().includes(userSearchQuery.value.toLowerCase())
        )
      }
    }
    
    // 查看用户详情
    const viewUserDetails = (user) => {
      ElMessage.info(`查看用户: ${user.username} (ID: ${user.id})`)
    }
    
    // 编辑用户
    const editUser = (user) => {
      editingUser.value = {
        id: user.id,
        username: user.username,
        name: user.name || '',
        gender: user.gender || 1,
        job: user.job || 0,
        phone: user.phone || '',
        qq: user.qq || '',
        address: user.address || '',
        avatar: user.avatar || ''
      }
      showEditUser.value = true
    }
    
    // 删除用户
    const deleteUser = async (user) => {
      try {
        const confirmed = await ElMessageBox.confirm(
          `确定要删除用户 "${user.username}" 吗？此操作不可撤销。`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        if (confirmed) {
          console.log('开始删除用户:', user.id, '请求URL:', `/users/${user.id}`)
          console.log('请求头Token:', store.state.token ? '已设置' : '未设置')
          
          const response = await fetch(`/users/${user.id}`, {
            method: 'DELETE',
            headers: {
              'Authorization': `Bearer ${store.state.token}`
            }
          })
          
          console.log('删除请求响应状态:', response.status, response.statusText)
          console.log('响应头:', Object.fromEntries(response.headers.entries()))
          
          if (!response.ok) {
            console.error('HTTP错误:', response.status, response.statusText)
            ElMessage.error(`删除失败: HTTP ${response.status}`)
            return
          }
          
          const result = await response.json()
          console.log('删除请求响应数据:', result)
          
          if (result.code === 1) {
            ElMessage.success('用户删除成功')
            await fetchAllUsers() // 刷新用户列表
          } else {
            console.error('删除失败，服务器返回:', result)
            ElMessage.error(result.msg || '删除失败')
          }
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除用户失败详细错误:', error)
          console.error('错误类型:', error.name)
          console.error('错误消息:', error.message)
          console.error('错误堆栈:', error.stack)
          ElMessage.error(`删除失败: ${error.message || '请稍后重试'}`)
        }
      }
    }
    
    // 处理用户编辑头像上传
    const handleEditAvatarUpload = (event) => {
      const file = event.target.files[0]
      if (!file) return
      
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        ElMessage.error('请选择图片文件')
        return
      }
      
      // 检查文件大小（限制为2MB）
      if (file.size > 2 * 1024 * 1024) {
        ElMessage.error('图片大小不能超过2MB')
        return
      }
      
      // 转换为Base64
      const reader = new FileReader()
      reader.onload = (e) => {
        editingUser.value.avatar = e.target.result
      }
      reader.readAsDataURL(file)
    }
    
    // 保存用户编辑
    const saveUserEdit = async () => {
      try {
        const response = await fetch(`/users/${editingUser.value.id}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${store.state.token}`
          },
          body: JSON.stringify({
            name: editingUser.value.name,
            gender: editingUser.value.gender,
            job: editingUser.value.job,
            phone: editingUser.value.phone,
            qq: editingUser.value.qq,
            address: editingUser.value.address,
            avatar: editingUser.value.avatar
          })
        })
        
        const result = await response.json()
        if (result.code === 1) {
          ElMessage.success('用户信息更新成功')
          showEditUser.value = false
          editingUser.value = {}
          await fetchAllUsers() // 刷新用户列表
        } else {
          ElMessage.error(result.msg || '更新失败')
        }
      } catch (error) {
        console.error('保存用户编辑失败:', error)
        ElMessage.error('保存失败，请稍后重试')
      }
    }
    
    // 获取性别文本
    const getGenderText = (gender) => {
      if (gender === 1) return '男'
      if (gender === 2) return '女'
      return '暂无数据'
    }
    
    // 获取职位文本
    const getJobText = (job) => {
      if (job === 1) return '班主任'
      if (job === 2) return '讲师'
      if (job === 3) return '学工主管'
      if (job === 4) return '学生'
      return '暂无数据'
    }
    
    // 开始编辑个人资料
    const startEditProfile = () => {
      isEditingProfile.value = true
      originalUserInfo.value = { ...userInfo.value }
      editUserInfo.value = {
        name: userInfo.value.name || '',
        gender: userInfo.value.gender || 1,
        phone: userInfo.value.phone || '',
        avatar: userInfo.value.avatar || '',
        qq: userInfo.value.qq || '',
        address: userInfo.value.address || ''
      }
    }
    
    // 处理头像上传
    const handleAvatarUpload = (event) => {
      const file = event.target.files[0]
      if (!file) return
      
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        ElMessage.error('请选择图片文件')
        return
      }
      
      // 检查文件大小（限制为2MB）
      if (file.size > 2 * 1024 * 1024) {
        ElMessage.error('图片大小不能超过2MB')
        return
      }
      
      // 转换为Base64
      const reader = new FileReader()
      reader.onload = (e) => {
        editUserInfo.value.avatar = e.target.result
      }
      reader.readAsDataURL(file)
    }
    
    // 取消编辑个人资料
    const cancelEditProfile = () => {
      isEditingProfile.value = false
      editUserInfo.value = {}
      originalUserInfo.value = {}
    }
    
    // 保存个人资料
    const saveProfile = async () => {
      try {
        const response = await fetch('/users/update-profile', {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${store.state.token}`
          },
          body: JSON.stringify(editUserInfo.value)
        })
        
        const result = await response.json()
        if (result.code === 1) {
          // 更新本地用户信息
          userInfo.value = { ...userInfo.value, ...editUserInfo.value }
          isEditingProfile.value = false
          editUserInfo.value = {}
          originalUserInfo.value = {}
          ElMessage.success('个人资料更新成功')
        } else {
          ElMessage.error(result.msg || '更新失败')
        }
      } catch (error) {
        console.error('保存个人资料失败:', error)
        ElMessage.error('保存失败，请稍后重试')
      }
    }

    return {
      prizes,
      wheelRotation,
      isSpinning,
      showWinModal,
      currentPrize,
      userWinningRecords,
      allWinningRecords,
      attemptsLeft,
      showPrizeSettings,
      showAllRecords,
      isTeacher,
      currentUserId,
      username,
      isAuthenticated,
      displayUsername,
      showStockWindow,
      stockWindowMinimized,
      fetchUserWinningRecords,
      fetchAllWinningRecords,
      loadPrizes,
      addPrize,
      removePrize,
      savePrizes,
      getSectorPath,
      getSectorColor,
      getSectorImageX,
      getSectorImageY,
      getSectorImageSize,
      getSectorTextX,
      getSectorTextY,
      spinWheel,
      closeWinModal,
      triggerFileInput,
      handleImageUpload,
      validatePrizes,
      isSaving,
      getPrizeImage,
      handleImageError,
      getStockPercentage,
      getStockColor,
      startStockRefresh,
      stopStockRefresh,
      logout,
      // 新增的变量和方法
      showProfile,
      showUserManagement,
      userInfo,
      userStats,
      allUsers,
      filteredUsers,
      userSearchQuery,
      winRate,
      formatDate,
      fetchUserInfo,
      fetchUserStats,
      fetchAllUsers,
      openUserManagement,
      filterUsers,
      viewUserDetails,
      editUser,
      // 编辑个人资料相关
      isEditingProfile,
      editUserInfo,
      getGenderText,
      startEditProfile,
      cancelEditProfile,
      saveProfile,
      handleAvatarUpload,
      // 用户编辑相关
      showEditUser,
      editingUser,
      deleteUser,
      handleEditAvatarUpload,
      saveUserEdit,
      getJobText
    }
  }
}
</script>

<style scoped>
.roulette {
  text-align: center;
  font-family: Arial, sans-serif;
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

/* 欢迎区域样式 */
.welcome-section {
  position: fixed;
  top: 20px;
  left: 20px;
  z-index: 100;
  animation: welcomeSlideIn 0.8s ease-out;
}

@keyframes welcomeSlideIn {
  from {
    opacity: 0;
    transform: translateX(-100px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.welcome-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 25px;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
  display: flex;
  align-items: center;
  gap: 15px;
  width: 280px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.welcome-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 40px rgba(102, 126, 234, 0.4);
}

.welcome-icon {
  background: rgba(255, 255, 255, 0.2);
  padding: 12px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.welcome-icon svg {
  color: white;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}

.welcome-content {
  flex: 1;
  text-align: left;
}

.welcome-title {
  margin: 0 0 5px 0;
  font-size: 18px;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.welcome-username {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 700;
  color: #FFD700;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.welcome-subtitle {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
  font-weight: 400;
}

/* 退出按钮区域样式 */
.logout-section {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 100;
  animation: logoutSlideIn 0.8s ease-out;
}

@keyframes logoutSlideIn {
  from {
    opacity: 0;
    transform: translateX(100px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.logout-btn {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 4px 15px rgba(255, 107, 107, 0.3);
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.logout-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255, 107, 107, 0.4);
  background: linear-gradient(135deg, #ff5252 0%, #d32f2f 100%);
}

.logout-btn:hover svg {
  transform: translateX(2px);
}

.logout-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 10px rgba(255, 107, 107, 0.3);
}

.logout-btn svg {
  transition: transform 0.3s ease;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .welcome-section {
    position: relative;
    top: auto;
    left: auto;
    margin-bottom: 20px;
  }
  
  .welcome-card {
    min-width: auto;
    width: 100%;
    max-width: 350px;
    margin: 0 auto;
  }
  
  .logout-section {
    position: relative;
    top: auto;
    right: auto;
    margin-bottom: 20px;
    text-align: center;
  }
  
  .logout-btn {
    font-size: 12px;
    padding: 10px 16px;
  }
  
  .stock-window {
    top: 120px;
    right: 10px;
    left: 10px;
    width: auto;
    max-height: 400px;
  }
  
  .stock-content {
    max-height: 300px;
    padding: 10px;
  }
}



.wheel-container {
  position: relative;
  display: inline-block;
}

/* 库存窗口样式 */
.stock-window {
  position: fixed;
  top: 80px;
  right: 20px;
  width: 320px;
  max-height: 600px;
  background: white;
  border: 2px solid #e0e0e0;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 99;
  transition: all 0.3s ease;
}

.stock-window.minimized {
  height: 50px;
  overflow: hidden;
}

.stock-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 12px 16px;
  border-radius: 8px 8px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  user-select: none;
}

.stock-header:hover {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

.stock-header .header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.stock-header .minimize-btn {
  font-size: 14px;
  transition: transform 0.3s ease;
  cursor: pointer;
  padding: 4px;
}

.stock-header .close-modal {
  font-size: 20px;
  cursor: pointer;
  color: rgba(255, 255, 255, 0.8);
  line-height: 1;
  padding: 4px;
  background: rgba(255, 255, 255, 0.1);
  border: none;
  border-radius: 50%;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.stock-header .close-modal:hover {
  color: white;
  background: rgba(255, 255, 255, 0.2);
  transform: scale(1.1);
}

.stock-content {
  max-height: 500px;
  overflow-y: auto;
  padding: 15px;
}

.stock-item {
  margin-bottom: 12px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.stock-prize-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.stock-prize-image {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 6px;
  border: 2px solid #e0e0e0;
}

.stock-prize-details {
  flex: 1;
}

.stock-prize-name {
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
  font-size: 14px;
}

.stock-numbers {
  display: flex;
  gap: 12px;
  margin-bottom: 6px;
  font-size: 12px;
}

.stock-remaining {
  font-weight: bold;
  padding: 2px 6px;
  border-radius: 4px;
  background: #e8f5e8;
  color: #2ed573;
}

.stock-remaining.low-stock {
  background: #fff3cd;
  color: #ffa502;
}

.stock-remaining.out-of-stock {
  background: #f8d7da;
  color: #ff4757;
}

.stock-total {
  color: #666;
}

.stock-progress {
  width: 100%;
  height: 6px;
  background: #e0e0e0;
  border-radius: 3px;
  overflow: hidden;
}

.stock-progress-bar {
  height: 100%;
  transition: all 0.3s ease;
  border-radius: 3px;
}

.no-stock-data {
  text-align: center;
  color: #999;
  padding: 20px;
  font-style: italic;
}

.stock-btn {
  background: linear-gradient(135deg, #2196F3, #1565C0);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 25px;
  cursor: pointer;
  font-weight: bold;
  font-size: 14px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(33, 150, 243, 0.3);
  min-width: 140px;
  margin: 5px;
}

.stock-btn:hover {
  background: linear-gradient(135deg, #1976D2, #0D47A1);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(33, 150, 243, 0.4);
}

.info-section {
  margin: 20px 0;
}

.wheel {
  transition: transform 4s cubic-bezier(0.25, 0.1, 0.25, 1);
}

.wheel-center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -80%);
  width: 80px;
  height: 80px;
  background: linear-gradient(45deg, #FFD700, #FFA500);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 8px rgba(0,0,0,0.3);
  border: 3px solid #FFD700;
}

.go-button {
  color: #333;
  font-size: 24px;
  font-weight: bold;
  text-shadow: 1px 1px 2px rgba(255,255,255,0.8);
}

.attempts {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

.user-records {
  margin-top: 30px;
  border: none;
  padding: 0;
  border-radius: 15px;
  background: linear-gradient(135deg, #ffffff, #f8f9fa);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.user-records h3 {
  margin: 0;
  padding: 20px 25px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  font-size: 18px;
  font-weight: 600;
  text-align: center;
  letter-spacing: 0.5px;
}

.records-table {
  width: 100%;
  border-collapse: collapse;
  margin: 0;
  background: white;
}

.records-table th,
.records-table td {
  border: none;
  padding: 15px 20px;
  text-align: left;
  border-bottom: 1px solid #e9ecef;
}

.records-table th {
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  font-weight: 600;
  color: #495057;
  font-size: 14px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.records-table td {
  color: #6c757d;
  font-size: 14px;
  transition: all 0.3s ease;
}

.records-table tr:hover {
  background: linear-gradient(135deg, #f8f9fa, #ffffff);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.prize-image-cell {
  text-align: center;
  padding: 10px !important;
}

.prize-image-small {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 8px;
  border: 2px solid #e9ecef;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.prize-image-small:hover {
  transform: scale(1.1);
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.no-image {
  display: inline-block;
  width: 50px;
  height: 50px;
  line-height: 50px;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  border: 2px dashed #dee2e6;
  border-radius: 8px;
  color: #6c757d;
  font-size: 12px;
  text-align: center;
}

.records-table tr:hover td {
  color: #495057;
}

.records-table tbody tr:last-child td {
  border-bottom: none;
}

.no-records {
  text-align: center;
  color: #6c757d;
  padding: 40px 20px;
  font-size: 16px;
  font-style: italic;
  background: white;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

table th, table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

table th {
  background-color: #f2f2f2;
}

.win-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 30px;
  border-radius: 10px;
  text-align: center;
  position: relative;
  max-width: 400px;
  width: 90%;
}

.close {
  position: absolute;
  top: 10px;
  right: 15px;
  font-size: 24px;
  cursor: pointer;
}

.prize-image-large {
  width: 150px;
  height: 150px;
  object-fit: contain;
  margin-bottom: 15px;
}

.prize-form {
  margin-bottom: 25px;
  padding: 25px;
  border: none;
  border-radius: 15px;
  background: linear-gradient(135deg, #ffffff, #f8f9fa);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(102, 126, 234, 0.1);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.prize-form::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 15px 15px 0 0;
}

.prize-form:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
  border-color: rgba(102, 126, 234, 0.3);
}

.prize-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  font-weight: 600;
  font-size: 16px;
  color: #667eea;
  padding-bottom: 15px;
  border-bottom: 2px solid rgba(102, 126, 234, 0.1);
}

.close-btn {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  color: white;
  border: none;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  cursor: pointer;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
}

.close-btn:hover {
  background: linear-gradient(135deg, #ff5252, #e53935);
  transform: scale(1.1);
  box-shadow: 0 6px 16px rgba(255, 107, 107, 0.4);
}

.form-group {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.form-group label {
  min-width: 120px;
  font-weight: 600;
  color: #495057;
  font-size: 14px;
}

.form-group input, .form-group select {
  padding: 12px 16px;
  border: 2px solid rgba(102, 126, 234, 0.2);
  border-radius: 12px;
  flex: 1;
  font-size: 14px;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.8);
}

.form-group input:focus, .form-group select:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  background: #ffffff;
}

.form-group input:hover, .form-group select:hover {
  border-color: rgba(102, 126, 234, 0.4);
}

.upload-btn {
  background: linear-gradient(135deg, #4CAF50, #45a049);
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 12px;
  cursor: pointer;
  font-weight: 600;
  font-size: 14px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
}

.upload-btn:hover {
  background: linear-gradient(135deg, #45a049, #388e3c);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(76, 175, 80, 0.4);
}

.prize-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 12px;
  border: 3px solid rgba(102, 126, 234, 0.2);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.prize-image:hover {
  transform: scale(1.05);
  border-color: #667eea;
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.3);
}

.add-prize-btn, .save-btn, .cancel-btn {
  margin: 8px;
  padding: 14px 28px;
  border: none;
  border-radius: 25px;
  cursor: pointer;
  font-weight: 600;
  font-size: 14px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.add-prize-btn {
  background: linear-gradient(135deg, #2196F3, #1976D2);
  color: white;
  box-shadow: 0 4px 15px rgba(33, 150, 243, 0.3);
}

.add-prize-btn:hover {
  background: linear-gradient(135deg, #1976D2, #1565C0);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(33, 150, 243, 0.4);
}

.save-btn {
  background: linear-gradient(135deg, #4CAF50, #45a049);
  color: white;
  box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3);
}

.save-btn:hover {
  background: linear-gradient(135deg, #45a049, #388e3c);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(76, 175, 80, 0.4);
}

.save-btn:disabled {
  background: linear-gradient(135deg, #cccccc, #999999);
  cursor: not-allowed;
  opacity: 0.6;
  transform: none;
  box-shadow: none;
}

.save-btn:disabled:hover {
  background: linear-gradient(135deg, #cccccc, #999999);
  transform: none;
  box-shadow: none;
}

.cancel-btn {
  background: linear-gradient(135deg, #f44336, #d32f2f);
  color: white;
  box-shadow: 0 4px 15px rgba(244, 67, 54, 0.3);
}

.cancel-btn:hover {
  background: linear-gradient(135deg, #d32f2f, #c62828);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(244, 67, 54, 0.4);
}

.control-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-top: 15px;
  flex-wrap: wrap;
}

.settings-btn, .records-btn {
  background: linear-gradient(135deg, #FF9800, #FF6F00);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 25px;
  cursor: pointer;
  font-weight: bold;
  font-size: 14px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(255, 152, 0, 0.3);
  min-width: 140px;
}

.settings-btn:hover, .records-btn:hover {
  background: linear-gradient(135deg, #F57C00, #E65100);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255, 152, 0, 0.4);
}

.records-btn {
  background: linear-gradient(135deg, #2196F3, #1565C0);
  box-shadow: 0 4px 15px rgba(33, 150, 243, 0.3);
}

.records-btn:hover {
  background: linear-gradient(135deg, #1976D2, #0D47A1);
  box-shadow: 0 6px 20px rgba(33, 150, 243, 0.4);
}

.prize-name-svg {
  font-size: 12px;
  font-weight: bold;
  fill: #333;
  text-shadow: 1px 1px 2px rgba(255, 255, 255, 0.8);
}

.prize-image-svg {
  border-radius: 8px;
  filter: drop-shadow(2px 2px 4px rgba(0, 0, 0, 0.3));
  transition: all 0.3s ease;
}

.prize-image-svg:hover {
  filter: drop-shadow(3px 3px 6px rgba(0, 0, 0, 0.4)) brightness(1.1);
}

/* 奖品设置弹窗样式 */
.prize-settings-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(5px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: modalFadeIn 0.3s ease-out;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.prize-settings-content {
  background: linear-gradient(135deg, #ffffff, #f8f9fa);
  border-radius: 20px;
  max-width: 700px;
  width: 90%;
  max-height: 85vh;
  overflow-y: auto;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3), 0 8px 32px rgba(102, 126, 234, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.2);
  animation: contentSlideIn 0.4s ease-out 0.1s both;
}

@keyframes contentSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 全部用户中奖记录弹窗样式 */
.all-records-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.all-records-content {
  background-color: white;
  border-radius: 10px;
  max-width: 900px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25px 35px;
  border-bottom: none;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 20px 20px 0 0;
  position: relative;
}

.modal-header::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
}

.modal-header h3 {
  margin: 0;
  color: white;
  font-size: 22px;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.close-modal {
  font-size: 32px;
  cursor: pointer;
  color: rgba(255, 255, 255, 0.8);
  line-height: 1;
  padding: 8px;
  background: rgba(255, 255, 255, 0.1);
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.close-modal:hover {
  color: white;
  background: rgba(255, 255, 255, 0.2);
  transform: scale(1.1);
}

.modal-body {
  padding: 30px 35px;
  max-height: 55vh;
  overflow-y: auto;
  background: linear-gradient(135deg, #ffffff, #f8f9fa);
}

.modal-body::-webkit-scrollbar {
  width: 8px;
}

.modal-body::-webkit-scrollbar-track {
  background: rgba(102, 126, 234, 0.1);
  border-radius: 4px;
}

.modal-body::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 4px;
}

.modal-body::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(135deg, #5a67d8, #6b46c1);
}

.modal-footer {
  padding: 25px 35px;
  border-top: none;
  background: linear-gradient(135deg, #f8f9fa, #ffffff);
  border-radius: 0 0 20px 20px;
  text-align: center;
  position: relative;
}

.modal-footer::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(102, 126, 234, 0.2), transparent);
}

/* 库存管理样式 */
.form-group input[type="number"] {
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.9);
  width: 100%;
  box-sizing: border-box;
}

.form-group input[type="number"]:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  background: white;
}

.form-group input[type="number"]:invalid {
  border-color: #f44336;
  box-shadow: 0 0 0 3px rgba(244, 67, 54, 0.1);
}

.error-text {
  color: #f44336;
  font-size: 12px;
  margin-top: 4px;
  display: block;
  font-weight: 500;
  animation: errorFadeIn 0.3s ease-out;
}

@keyframes errorFadeIn {
  from {
    opacity: 0;
    transform: translateY(-5px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 库存状态指示器 */
.stock-indicator {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: bold;
  margin-left: 8px;
}

.stock-indicator.low {
  background: #ffebee;
  color: #c62828;
}

.stock-indicator.medium {
  background: #fff3e0;
  color: #ef6c00;
}

.stock-indicator.high {
  background: #e8f5e8;
  color: #2e7d32;
}

.stock-indicator.empty {
  background: #ffcdd2;
  color: #d32f2f;
}

/* 左侧功能区域样式 */
.left-sidebar {
  position: fixed;
  top: 150px;
  left: 20px;
  z-index: 90;
  animation: sidebarSlideIn 0.8s ease-out;
}

@keyframes sidebarSlideIn {
  from {
    opacity: 0;
    transform: translateX(-100px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.sidebar-card {
  background: linear-gradient(135deg, #69c9f3 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(128, 135, 166, 0.3);
  width: 290px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.sidebar-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 40px rgba(102, 126, 234, 0.4);
}

.sidebar-title {
  margin: 0 0 15px 0;
  font-size: 16px;
  font-weight: 600;
  text-align: center;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.sidebar-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.sidebar-btn {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  color: white;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
}

.sidebar-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateX(5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.btn-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
}

.profile-btn:hover {
  background: linear-gradient(135deg, rgba(76, 175, 80, 0.3), rgba(139, 195, 74, 0.3));
}

.admin-btn:hover {
  background: linear-gradient(135deg, rgba(255, 152, 0, 0.3), rgba(255, 193, 7, 0.3));
}

/* 个人资料弹窗样式 */
.profile-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.profile-content {
  background: linear-gradient(135deg, #ffffff, #f8f9fa);
  border-radius: 20px;
  max-width: 650px;
  width: 90%;
  max-height: 85vh;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15), 0 8px 20px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.modal-header {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  padding: 25px 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 20px 20px 0 0;
}

.modal-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.modal-header h3::before {
  content: '👤';
  margin-right: 10px;
  font-size: 18px;
}

.modal-body {
  padding: 30px;
  max-height: calc(85vh - 140px);
  overflow-y: auto;
}

.modal-body::-webkit-scrollbar {
  width: 6px;
}

.modal-body::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.modal-body::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 3px;
}

.modal-body::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(135deg, #5a6fd8, #6a4190);
}

.profile-info {
  margin-bottom: 0;
}

.close-modal {
  font-size: 28px;
  cursor: pointer;
  color: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
}

.close-modal:hover {
  color: white;
  background: rgba(255, 255, 255, 0.2);
  transform: rotate(90deg);
}

.modal-footer {
  padding: 20px 30px;
  border-top: 1px solid #f0f2f5;
  background: rgba(248, 249, 250, 0.5);
  border-radius: 0 0 20px 20px;
  display: flex;
  justify-content: center;
}

.cancel-btn {
  background: linear-gradient(135deg, #6c757d, #495057);
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 25px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
  font-size: 14px;
}

.cancel-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(108, 117, 125, 0.3);
}

.profile-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 0;
  border-bottom: 1px solid #f0f2f5;
  transition: all 0.3s ease;
}

.profile-item:hover {
  background: rgba(102, 126, 234, 0.02);
  border-radius: 8px;
  margin: 0 -15px;
  padding: 18px 15px;
}

.profile-item:last-child {
  border-bottom: none;
}

.profile-item label {
  font-weight: 600;
  color: #2c3e50;
  min-width: 120px;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.profile-item label::before {
  content: '';
  width: 4px;
  height: 4px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 50%;
  margin-right: 8px;
}

.profile-value {
  color: #34495e;
  flex: 1;
  text-align: right;
  font-weight: 500;
  font-size: 14px;
  padding: 8px 12px;
  background: rgba(102, 126, 234, 0.05);
  border-radius: 6px;
  min-height: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.address-text {
  text-align: left !important;
  justify-content: flex-start !important;
  word-break: break-all;
  line-height: 1.4;
}

.profile-stats {
  background: linear-gradient(135deg, #f8f9fa, #ffffff);
  padding: 20px;
  border-radius: 12px;
  border: 1px solid #e9ecef;
}

.profile-stats h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 15px;
}

.stat-item {
  text-align: center;
  padding: 15px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.stat-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-label {
  display: block;
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
  font-weight: 500;
}

.stat-value {
  display: block;
  font-size: 20px;
  font-weight: 700;
  color: #667eea;
}

/* 编辑个人资料样式 */
.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.edit-btn, .save-btn, .cancel-edit-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.edit-btn {
  background: linear-gradient(135deg, #4CAF50, #8BC34A);
  color: white;
}

.edit-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}

.save-btn {
  background: linear-gradient(135deg, #2196F3, #21CBF3);
  color: white;
}

.save-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(33, 150, 243, 0.3);
}

.cancel-edit-btn {
  background: linear-gradient(135deg, #f44336, #ff5722);
  color: white;
}

.cancel-edit-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(244, 67, 54, 0.3);
}

.edit-input, .edit-select, .edit-textarea {
  flex: 1;
  padding: 8px 12px;
  border: 2px solid #e1e5e9;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: white;
}

.edit-input:focus, .edit-select:focus, .edit-textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.edit-textarea {
  resize: vertical;
  min-height: 60px;
  font-family: inherit;
}

.edit-select {
  cursor: pointer;
}

.profile-item {
  align-items: flex-start;
}

.profile-item:has(.edit-textarea) {
  align-items: flex-start;
}

.profile-item label {
  padding-top: 8px;
}

/* 用户管理弹窗样式 */
.user-management-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.user-management-content {
  background-color: white;
  border-radius: 20px;
  max-width: 1000px;
  width: 95%;
  max-height: 85vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}

.user-management-tools {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
}

.refresh-btn {
  padding: 10px 20px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.search-box {
  flex: 1;
  max-width: 300px;
}

.search-box input {
  width: 100%;
  padding: 10px 15px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.search-box input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.users-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

.users-table th,
.users-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #e9ecef;
}

.users-table th {
  background: linear-gradient(135deg, #f8f9fa, #ffffff);
  font-weight: 600;
  color: #333;
  position: sticky;
  top: 0;
  z-index: 10;
}

.users-table tr:hover {
  background-color: #f8f9fa;
}

.action-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
  margin-right: 5px;
  transition: all 0.3s ease;
}

.view-btn {
  background: linear-gradient(135deg, #4CAF50, #8BC34A);
  color: white;
}

.view-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}

.edit-btn {
  background: linear-gradient(135deg, #FF9800, #FFC107);
  color: white;
}

.edit-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(255, 152, 0, 0.3);
}

.no-users {
  text-align: center;
  padding: 40px;
  color: #666;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .left-sidebar {
    position: relative;
    top: auto;
    left: auto;
    margin: 20px 0;
  }
  
  .sidebar-card {
    min-width: auto;
    width: 100%;
  }
  
  .sidebar-buttons {
    flex-direction: row;
    justify-content: space-around;
  }
  
  .sidebar-btn {
    flex: 1;
    justify-content: center;
    padding: 10px;
  }
  
  .btn-icon {
    margin-right: 5px;
  }
  
  .profile-content,
  .user-management-content {
    width: 95%;
    margin: 10px;
  }
  
  .user-management-tools {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-box {
    max-width: none;
  }
  
  .users-table {
    font-size: 12px;
  }
  
  .users-table th,
  .users-table td {
    padding: 8px 4px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
}

/* 头像相关样式 */
.user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #667eea;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

/* 表格头像样式 */
.user-avatar-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8px;
}

.table-user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e1e5e9;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.table-user-avatar:hover {
  transform: scale(1.1);
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.default-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #f8f9fa;
  border: 2px solid #e1e5e9;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #6c757d;
  font-weight: 500;
}

.user-avatar:hover {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.avatar-upload {
  display: flex;
  flex-direction: column;
  gap: 10px;
  align-items: flex-start;
}

.upload-avatar-btn {
  padding: 8px 16px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.upload-avatar-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.preview-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e1e5e9;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.edit-btn {
  padding: 10px 20px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  margin-right: 10px;
}

.edit-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.save-btn {
  padding: 10px 20px;
  background: linear-gradient(135deg, #28a745, #20c997);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  margin-right: 10px;
}

.save-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
}

/* 欢迎区域头像样式 */
.welcome-avatar {
  display: flex;
  align-items: center;
  justify-content: center;
}

.welcome-user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.welcome-user-avatar:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
}

/* 用户编辑弹窗样式 */
.edit-user-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.edit-user-content {
  background: linear-gradient(135deg, #ffffff, #f8f9fa);
  border-radius: 20px;
  max-width: 650px;
  width: 90%;
  max-height: 85vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15), 0 8px 20px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.edit-user-info {
  margin-bottom: 0;
}

.edit-user-modal .modal-body {
  flex: 1;
  overflow-y: auto;
  padding: 30px;
}

.edit-profile-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 0;
  border-bottom: 1px solid #f0f2f5;
  transition: all 0.3s ease;
}

.edit-profile-item:hover {
  background: rgba(102, 126, 234, 0.02);
  border-radius: 8px;
  margin: 0 -15px;
  padding: 18px 15px;
}

.edit-profile-item:last-child {
  border-bottom: none;
}

.edit-profile-item label {
  font-weight: 600;
  color: #2c3e50;
  min-width: 120px;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.edit-profile-item label::before {
  content: '';
  width: 4px;
  height: 4px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 50%;
  margin-right: 8px;
}

.edit-profile-item:has(.edit-textarea) {
  align-items: flex-start;
}

.edit-profile-item:has(.edit-textarea) label {
  padding-top: 8px;
}



.delete-btn {
  background: linear-gradient(135deg, #dc3545, #c82333);
  color: white;
}

.delete-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(220, 53, 69, 0.3);
}

.cancel-btn {
  padding: 10px 20px;
  background: linear-gradient(135deg, #6c757d, #5a6268);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(108, 117, 125, 0.3);
}

/* 编辑用户模态框的footer样式 */
.edit-user-modal .modal-footer {
  padding: 20px 30px;
  border-top: 1px solid #f0f2f5;
  background: rgba(248, 249, 250, 0.5);
  border-radius: 0 0 20px 20px;
  display: flex;
  justify-content: center;
  gap: 15px;
}

/* 响应式设计 - 用户编辑弹窗 */
@media (max-width: 768px) {
  .edit-user-content {
    width: 95%;
    margin: 10px;
  }
  
  .edit-profile-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .edit-profile-item label {
    min-width: auto;
    margin-bottom: 5px;
  }
  
  .edit-input, .edit-select, .edit-textarea {
    width: 100%;
  }
}
</style>